package mx.tools;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import groovy.lang.Closure;

public class BubblePool<T> {
	int maxsize = 10;
	private HashMap keyMap = new HashMap();
	private HashMap objMap = new HashMap();
	private ArrayList objList = new ArrayList();
	Creator creator;
	
	public BubblePool(Creator creator, int maxsize) {
		this.creator = creator;
		this.maxsize = maxsize;
	}
	
	private void addObjToPool(String key, Object o) {
		if(objList.size()>this.maxsize){                   //如果超过容量，
			objMap.remove(objList.get(objList.size()-1));  //从对象池中删除最后一个对象.
			keyMap.remove(objList.get(objList.size()-1));  //从KEYMAP中删除KEY的位置
			objList.remove(objList.size()-1);              //从KEY链表中删除最后一个key。
		}
		objMap.put(key, o);                                //将新建对象放入对象池中.
		objList.add(key);                                  //将新建对象的KEY加入到KEY链表.
		keyMap.put(key, objList.size()-1);                 //将KEY在链表中的位置放入KEYMAP中.
	}	
	
	//做冒泡处理，
	private void bubble(String key) {
		int i = (Integer) keyMap.get(key);
		if (i>0) {
			Object obj = objList.get(i-1);
			objList.set(i-1, objList.get(i));
			objList.set(i, obj);
			
			keyMap.put(obj, i);
			keyMap.put(objList.get(i-1), i-1);
		}
	}	
	
	public synchronized T get(String key) throws Exception {
		Object obj = objMap.get(key);
		if (null == obj) {
			obj = creator.create(key);
			addObjToPool(key, obj);
		} else {
			bubble(key);
		}
		return (T) obj;
	}
	
	public synchronized void clear() {
		this.keyMap.clear();
		this.objList.clear();
		this.objMap.clear();
	}
}

